package com.hqbzl.c1.cass;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class Testaba {
    static AtomicReference<String> resouce = new AtomicReference<>("A");

    public static void main(String[] args) {
        System.out.println("resouce.get() = " + resouce.get());
        change();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        final boolean b = resouce.compareAndSet("A", "B");
        log.debug("b= {}", b);
    }

    public static void change() {
        new Thread(() -> {
            log.debug("r1 change before: {}", resouce.get());
            while (true) {
                final String curr = resouce.get();
                if (resouce.compareAndSet(curr, "B")) {
                    break;
                }
            }
            log.debug("r1 change after: {}", resouce.get());
        }, "t1").start();
        new Thread(() -> {
            log.debug("r2 change before: {}", resouce.get());
            while (true) {
                final String curr = resouce.get();
                if (resouce.compareAndSet(curr, "A")) {
                    break;
                }
            }
            log.debug("r2 change after: {}", resouce.get());
        }, "t2").start();

    }

}
